package mirrormonkey.core.server;

import mirrormonkey.core.member.SearchKey;
import mirrormonkey.framework.entity.StaticEntityData;
import mirrormonkey.framework.entity.SyncEntity;

final class DummyMappingStackElement extends MappingStackElement {

	protected Class<? extends SyncEntity> connectedClass;

	public DummyMappingStackElement(MappingStack stack) {
		super(stack);
		prev = this;
		next = this;
	}

	@Override
	public boolean exists() {
		return false;
	}

	@Override
	public MappingStackElement addRef(boolean override, SearchKey search) {
		System.out.println(getClass().getName() + "addRef(): " + search);
		boolean existed = stack.exists();
		ExistingMappingStack ems = stack.create();
		MappingStackElement insertBefore = ems.find(connectedClass,
				FindMode.FIRST_COMPATIBLE, FailMode.INCOMPATIBLE);
		System.out.println("insert before: " + insertBefore);
		ExistingMappingStackElement e = new ExistingMappingStackElement(ems,
				insertBefore, insertBefore.next, ems.module.getEntityProvider()
						.getStaticData(ems.entityData.getEntity().getClass(),
								connectedClass, true), search);
		if (!existed) {
			System.out.println("register");
			ems.register();
		} else if (!e.next.exists()) {
			System.out.println("notify change");
			e.notifyChange((ExistingMappingStackElement) e.prev);
		}
		return e;
	}

	@Override
	public MappingStackElement removeRef() {
		return this;
	}

	@Override
	public MappingStackElement cutTop() {
		return this;
	}

	@Override
	public MappingStackElement cutBottom() {
		return this;
	}

	@Override
	public MappingStackElement destroy() {
		return this;
	}

	@Override
	public boolean matchesExactly(Class<? extends SyncEntity> connectedClass) {
		return true;
	}

	@Override
	public boolean matchesSubclass(Class<? extends SyncEntity> connectedClass) {
		return true;
	}

	@Override
	public boolean matchesSuperclass(Class<? extends SyncEntity> connectedClass) {
		return true;
	}

	@Override
	public StaticEntityData getStaticData() {
		throw new RuntimeException(
				"You are trying to get the static data of a dummy element."
						+ "There is no static data present on a dummy element.");
	}

	@Override
	public MappingStackElement find(Class<? extends SyncEntity> connectedClass,
			FindMode find, FailMode fail) {
		this.connectedClass = connectedClass;
		return this;
	}
}